//
//  PlayViewController.m
//  SBVideoCaptureDemo
//
//  Created by Pandara on 14-8-18.
//  Copyright (c) 2014年 Pandara. All rights reserved.
//

#import "PlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SBCaptureDefine.h"

@interface PlayViewController (){
    UISlider *_slider;
    BOOL _sliderDraging;
}

@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) NSURL *videoFileURL;
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) UIButton *playButton;
@property (strong, nonatomic) AVPlayerItem *playerItem;
@property (strong, nonatomic) id playbackTimeObserver;

@end

@implementation PlayViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withVideoFileURL:(NSURL *)videoFileURL {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.videoFileURL = videoFileURL;
        self.autoPlay = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = self.autoPlay;
    if (!self.autoPlay){
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"使用" style:UIBarButtonItemStylePlain target:self action:@selector(pressDoneButton:)];
    }
    //self.view.backgroundColor = [UIColor colorWithRed:16 / 255.0f green:16 / 255.0f blue:16 / 255.0f alpha:1.0f];
    self.view.backgroundColor = [UIColor blackColor];

    /*self.backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
    [_backButton setImage:[UIImage imageNamed:@"vedio_nav_btn_back_nor.png"] forState:UIControlStateNormal];
    [_backButton setImage:[UIImage imageNamed:@"vedio_nav_btn_back_pre.png"] forState:UIControlStateHighlighted];
    [_backButton addTarget:self action:@selector(pressBackButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backButton];*/
    
    [self initPlayLayer];
    
    self.playButton = [[UIButton alloc] initWithFrame:_playerLayer.frame];
    [_playButton setImage:[UIImage imageNamed:@"video_icon.png"] forState:UIControlStateNormal];
    [_playButton addTarget:self action:@selector(pressPlayButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playButton];

    if (self.autoPlay){
        [self pressPlayButton:nil];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.title = @"视频播放";

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(avPlayerItemDidPlayToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

    [self.player pause];
    [self.player setRate:0];
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
    [_player removeTimeObserver:self.playbackTimeObserver];
}

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
}

- (void)initPlayLayer
{
    if (!_videoFileURL) {
        return;
    }
    
    NSFileManager *manager = [NSFileManager defaultManager];
    unsigned long long size = 0;
    if ([manager fileExistsAtPath:[_videoFileURL relativePath]]){
         size = [[manager attributesOfItemAtPath:[_videoFileURL relativePath] error:nil] fileSize];
    }

    NSLog(@"播放: %@, %lli kb", [_videoFileURL relativePath], size / 1024);

    
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:_videoFileURL options:nil];

    self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];

    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性

    _playerLayer.frame = CGRectMake(0, (DEVICE_SIZE.height - DEVICE_SIZE.width) / 2, DEVICE_SIZE.width, DEVICE_SIZE.width);
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;

    [self.view.layer addSublayer:_playerLayer];
    _slider = [[UISlider alloc] initWithFrame:CGRectMake(0, _playerLayer.frame.origin.y + _playerLayer.frame.size.height + 20, DEVICE_SIZE.width, 20)];
    _slider.minimumValue = 0;
    _slider.maximumValue = _playerItem.duration.value;
    _slider.value = self.player.currentTime.value;

    [_slider addTarget:self action:@selector(seekToTime:) forControlEvents:UIControlEventValueChanged];
    [_slider addTarget:self action:@selector(sliderDragEnter:) forControlEvents:UIControlEventTouchDragInside];


    [self.view addSubview: _slider];

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewClick:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    self.view.userInteractionEnabled = YES;
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

- (void)pressPlayButton:(UIButton *)button
{
    [_playerItem seekToTime:kCMTimeZero];
    [_player play];
    _playButton.alpha = 0.0f;
}

- (void)pressBackButton:(UIButton *)button
{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)pressDoneButton:(UIBarButtonItem *)button{
    if (self.payDelegate && [self.payDelegate respondsToSelector:@selector(pressDone:)]){
        [self.payDelegate pressDone:_videoFileURL];
    }
    [self pressBackButton:nil];
}

- (void)viewClick:(id) sender{
    self.navigationController.navigationBarHidden = !self.navigationController.navigationBarHidden;
}

- (void)seekToTime:(UISlider *)slider{
    /*[_player pause];
    [_playerItem seekToTime:CMTimeMakeWithSeconds(slider.value, _playerItem.currentTime.flags)];
    [_player play];*/
    CMTime newTime = CMTimeMakeWithSeconds(slider.value, 1);
    [_player seekToTime:newTime];
    NSLog(@"..go to %f", slider.value);
    _sliderDraging = NO;
}

- (void)sliderDragEnter:(UISlider *)slider{
    _sliderDraging = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - PlayEndNotification
- (void)avPlayerItemDidPlayToEnd:(NSNotification *)notification
{
    if ((AVPlayerItem *)notification.object != _playerItem) {
        return;
    }
    [UIView animateWithDuration:0.3f animations:^{
        _playButton.alpha = 1.0f;
    }];
}

- (void)customVideoSlider:(CMTime)duration {
    _slider.maximumValue = (float) CMTimeGetSeconds(duration);
    /*UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [_slider setMinimumTrackImage:transparentImage forState:UIControlStateNormal];
    [_slider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];*/
}

-(void)updateVideoSlider:(CGFloat)currentSecond{
    if (!_sliderDraging)
        _slider.value = currentSecond + 1;
}

- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    self.playbackTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        CGFloat currentSecond = playerItem.currentTime.value / playerItem.currentTime.timescale;// 计算当前在第几秒
        [self updateVideoSlider:currentSecond];
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
//            self.stateButton.enabled = YES;
            CMTime duration = self.playerItem.duration;// 获取视频总长度
             CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
             //_totalTime = [self convertTime:totalSecond];// 转换成播放时间
             [self customVideoSlider:duration];// 自定义UISlider外观
             NSLog(@"movie total duration:%f", CMTimeGetSeconds(duration));
            [self monitoringPlayback:self.playerItem];// 监听播放状态 } else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度 NSLog(@"Time Interval:%f",timeInterval);
        CMTime duration = self.playerItem.duration;
        Float64 totalDuration = CMTimeGetSeconds(duration);
        //[self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
//        [_slider setValue:(float) timeInterval animated:YES];
    }
}
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    Float64 startSeconds = CMTimeGetSeconds(timeRange.start);
    Float64 durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}


- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; if (second/3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [formatter stringFromDate:d]; return showtimeNew;
}

@end
